// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.pages.user;

import lichen.entities.user.User;
import lichen.services.Encoder;
import lichen.services.InvalidateUserException;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 * 用户登录时候的处理
 * @author jcai
 * @version $Revision: 225 $
 * @since 0.0.2
 */
public class LoginUser extends AbstractUserPage{
	@SuppressWarnings("unused")
	@Component(parameters={"value=user.email","validate=required,email"})
	private TextField emailField;

	@SuppressWarnings("unused")
	@Component(parameters={"value=user.password","validate=required"})
	private PasswordField passwordField;
	
	@Component
    private Form _userForm;
	@Inject
	private Encoder _encoder;
	/**
	 * 记录跳转过来的页面.
	 */
	private String fromPagePath;
	void onActivate(String pagePath){
		this.fromPagePath = pagePath;
	}
	String[] onPassivate(){
		if(this.fromPagePath!=null){
			return new String[]{fromPagePath};
		}else{
			return new String[]{};
		}
	}
	Object onActionFromUserForm(){
		User user = getUser();
		try {
			getUserService().loginUser(user.getEmail(),user.getPassword());
		} catch (InvalidateUserException e) {
			_userForm.recordError(emailField,e.getMessage());
			return null;
		}
		if(this.fromPagePath == null){
			return getIndexPage();
		}else{
			return _encoder.decodUrl(this.fromPagePath);
		}
	}
}
